package models

import (
	"database/sql"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"test_singo/utils"
	"time"
)

/*该模型类为解决循环引用的问题才改到这里，原计划放到app/user/ 下*/

type User struct {
	gorm.Model
	Username string
	Nickname string
	Password string
	Status   string
	Avatar   string `gorm:"size:100"`
}

const (
	PasswordCost        = iota
	Active       string = "active"
	InActive     string = "InActive"
	Suspend      string = "suspend"
)

func (user *User) SetPassword(password string) error {
	fromPassword, err := bcrypt.GenerateFromPassword([]byte(password), PasswordCost)
	if err != nil {
		utils.Log().Panic("设置密码失败", err)
	}
	user.Password = string(fromPassword)
	return nil
}

func (user *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err == nil
}

// UserInfo 用户信息
type UserInfo struct {
	ID     uint
	Name   string
	Gender string
	Hobby  string
}
// 快速入门
type UserInfo1 struct {
	gorm.Model
	Name  string
	Age   sql.NullString //字符串可为空
	Hobby string
}

// 结构体标签
type UserInfo2 struct {
	gorm.Model
	Name         string
	Age          sql.NullInt64
	Birthday     *time.Time
	Email        string  `gorm:"type:varchar(100);unique_index"`
	Role         string  `gorm:"size:255"`        // 设置字段大小为255
	MemberNumber *string `gorm:"default:'小丸子'"` // 设置会员号（member number）唯一并且不为空
	Num          int     `gorm:"AUTO_INCREMENT"`  // 设置 num 为自增类型
	Address      string  `gorm:"index:addr"`      // 给address字段创建名为addr的索引
	IgnoreMe     int     `gorm:"-"`               // 忽略本字段
}


// 使用Scan将多条结果扫描进事先准备好的结构体切片中
type Result struct {
	Date time.Time
	Total int
}


type Result1 struct {
	Name string
	Age  int
}


//func (u *UserInfo2) BeforeUpdate(tx *gorm.DB) (err error) {
//	if u.Name == "zhu" {
//		return errors.New("admin user not allowed to update")
//	}
//	return
//}